
	function MamuleViewModel() {
		var self = this;
		
		self.baseuri = 'http://localhost:3030/mamule';
		self.currentUser = ko.observable();
		self.currentView = ko.observable();
		self.views = ko.observableArray(["dashboard", "write", "prices","contact"]);

		/* login and register */
		self.username = ko.observable();
        self.password = ko.observable();
        
        /* user data*/
        self.admin = ko.observable(false);
        self.forename = ko.observable();
        self.surname = ko.observable();
        self.street = ko.observable();
        self.city = ko.observable();
        self.postal = ko.observable();

		/* mail recipients */
		self.recipients = ko.observableArray();
		self.r_company = ko.observable();
		self.r_forename = ko.observable();
		self.r_surname = ko.observable();
		self.r_street = ko.observable();
		self.r_postal = ko.observable();
		self.r_city = ko.observable();

		/* prices */
		self.price_zone1 = ko.observable();
		self.price_zone2 = ko.observable();
		self.price_zone3 = ko.observable();
		self.current_order_price = ko.observable('EUR 00,00');

	
		/* orders */
		self.orders = ko.observableArray();
		
		self.beginLogin = function() {
			$('#login').modal('show');
		}
		
		self.login = function() {
			$('#login').modal('hide');
			
			var targetURI = self.baseuri + "/user";
			var response = self.ajax(targetURI, 'GET', null, function(user){ 
				self.storeSession();
				self.initOrders();
				self.queryPrices();

				//user is admin
				if(user.admin == true)
					self.admin(true);


				self.forename(user.identity.name.givenName);
				self.surname(user.identity.name.surName);
				self.street(user.identity.address.residence);
				self.postal(user.identity.address.postcode);
				self.city(user.identity.address.locality);

			});

			return true;
		}
		
		self.logout = function(){
			self.username(null);
			self.password(null);
			
			$.removeCookie('m_user');
			$.removeCookie('m_password');
		}
		
		self.storeSession = function(){
			//set cookies
			$.cookie('m_user', self.username() );
			$.cookie('m_password', self.password() );
		}
		
		self.loadSession = function(){		
			var username = $.cookie('m_user');
			var password = $.cookie('m_password');
			
			if( username && password )
			{
				self.username(username);
				self.password(password);
				return self.login();
			
			}else
			{
				self.beginLogin();
			}
		}

		self.register = function() {
			$('#login').modal('hide');

			var userdata = {
				'username': self.username(), 
				'password': self.password()
			};

			var targetURI = self.baseuri + '/user/register';	
			var request = {
				url: targetURI,
				type: 'POST',
				contentType: "application/json",
				cache: false,
				dataType: 'json',
				data: JSON.stringify(userdata),
				statusCode: {
                    201: function () { 
                    	self.login(); 
                    }
				}
		    };
		    var response = $.ajax(request);
		}

		self.updateUser = function(){
			//put auf /user
			var data = {
			  username : self.username(),
			  identity : { 
			  		name : {
				      salutation : "",
				      givenName : self.forename(),
				      surName : self.surname(),
				    },
				  scorporation : {
				      salutation : "",
				      givenName : "",
				      surName : "",
				    },
				  address : {
				      residence : self.street(),
				      locality : self.city(),
				      postcode : self.postal(),
				      country : "",
				    }
			  }
			}

			var targetURI = self.baseuri + '/user';
			self.ajax(targetURI, 'PUT', data, function(data){ });


		}

		//returns the deferred’s promise object
		self.ajax = function(uri, method, data, success) {		
		    var request = {
			url: uri,
			type: method,
			contentType: "application/json",
			cache: false,
			dataType: 'json',
			data: JSON.stringify(data),
			beforeSend: function (xhr) {
				var hash = btoa(self.username() + ":" + self.password());    
				xhr.setRequestHeader("Authorization", "Basic " + hash); //Base64 encoding
			},
			error: function(jqXHR) {
			    //TODO: could cause troubles in IE since console.log is not available and IE stops processing js after an error
			    console.log("ajax error " + jqXHR.status);
				self.logout();
				self.beginLogin();
			},
			success : success
		    };
		    return $.ajax(request);
		}
		
		self.parseOrderNumber = function(number){
			var width  = 6;
			width -= number.toString().length;
			if ( width > 0 )
			{
			    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
			}
			
			return number + ""; // always return a string
		}

		self.parseCurrency = function(number){
			var numberStr = parseFloat(number).toFixed(2).toString();
			var numFormatDec = numberStr.slice(-2); /*decimal 00*/
			numberStr = numberStr.substring(0, numberStr.length-3); /*cut last 3 strings*/
			var numFormat = new Array;
			while (numberStr.length > 3) {
				numFormat.unshift(numberStr.slice(-3));
				numberStr = numberStr.substring(0, numberStr.length-3);
			}
			numFormat.unshift(numberStr);
			return "EUR "+numFormat.join('.')+','+numFormatDec; /*format 000.000.000,00 */
		}

		self.queryPrices = function(){
			var targetURI = self.baseuri + '/price';
			mvm.ajax(targetURI, 'GET', null, function(data){ 
				self.price_zone1(data.price_zone1); //inner austria
				self.price_zone2(data.price_zone2); //outta austria
				self.price_zone3(data.price_zone3); //outta europe
			});
		}

		self.updatePrices = function(){
			var targetURI = self.baseuri + '/price/set';
			var prices = {
				'price_zone1' : self.price_zone1(),
				'price_zone2' : self.price_zone2(),
				'price_zone3' : self.price_zone3()
			}
			console.log(prices);
			mvm.ajax(targetURI, 'POST', prices, function(data){ 
				console.log(data);
			});
		}

		self.initOrders = function(){
			//target url to receive / add orders
			var targetURI = self.baseuri + '/user/orders';
			var response = self.ajax(targetURI, 'GET', null, function(data){
				var orders = Array();
			
				$.each(data, function(i, item) {
				   var parsedBody =  data[i].items.length + " items <br> ";
				   $.each(data[i].items, function(j, item){
					parsedBody +=  "item: "+ item.text.substring(0, 55);
					parsedBody += "<br>"
				   });
				
				   var parsedOrder = {
				   	id: data[i].id,
					title: ko.observable( data[i].date.substring(0,10) +" <br/>#"+ self.parseOrderNumber(data[i].id) ),
					body: ko.observable( parsedBody ),
					transient: ko.observable( (data[i].state == 'TRANSIENT')? true : false ),
					confirmed: ko.observable( (data[i].state == 'CONFIRMED')? true : false )
				   };
				   orders.push( parsedOrder );
				});
				
				self.orders ( orders );
			} );
		}

		self.addRecipient = function(){
			var newrecipient = {
				"company"		: self.r_company(), 
				"forename" 		: self.r_forename(),
				"surname"		: self.r_surname(),
				"street"		: self.r_street(),
				"postal"		: self.r_postal(),
				"city"			: self.r_city() 
			};
			self.recipients.push(newrecipient);

			//update price
			var price = parseInt( self.current_order_price().toString().replace("EUR ", "").replace(",", ".") );
			price += ( self.postal().length == 4 )? self.price_zone1() : self.price_zone2();
			self.current_order_price( self.parseCurrency(price) );
			
			//reset fields?
			self.r_company(null);
			self.r_forename(null);
			self.r_surname(null);
			self.r_street(null);
			self.r_postal(null);
			self.r_city(null);
		}

		self.removeRecipient = function (recipient){

			//update price
			var price = parseInt( self.current_order_price().toString().replace("EUR ", "").replace(",", ".") );
			price -= ( recipient.postal.length == 4 )? self.price_zone1() : self.price_zone2();
			self.current_order_price( self.parseCurrency(price) );

			self.recipients.remove(recipient);
		}

		self.sendMail = function(){
			var orderid = null;
			var mailid = null;
			
			//create order
			//post to /user/orders, take orderid
			var targetURI = self.baseuri + "/user/orders";
			self.ajax(targetURI, 'POST', null, function(data){ 
				orderid = data.message;
				console.log("orderid: "+orderid);	
				
				//create mail
				//post to /mail, take mail id
				var targetURI = self.baseuri + "/mail";
				self.ajax(targetURI, 'POST', null, function(data){ 
					mailid = data.message;
					console.log("mailid: "+mailid);
					
					//attach mail to order
					//put to user/orders/{id}  -> params { "items" : [ id, id, ... ] }
					var targetURI = self.baseuri + "/user/orders/"+orderid;
					var items = {'items': Array(mailid)};
					console.log(items);
					self.ajax(targetURI, 'PUT', items, function(data){ 
						console.log(data);
						
						//supercrazy - now send mails details
						//put: /mail/{mail-id}/text
						var targetURI = self.baseuri + "/mail/"+mailid;
						var recipients = Array();

							$.each(mvm.recipients(), function(key, rec){
							    
								if (rec.company=="" || rec.company == null)	//private	
								    var currentRecipient = {
									  name : {
									      salutation : "",
									      givenName : rec.forename,
									      surName : rec.surname,
									    },
									  corporation : {
									      salutation : "",
									      givenName : "",
									      surName : "",
									    },
									  address : {
									      residence : rec.street,
									      locality : rec.city,
									      postcode : rec.postal,
									      country : "",
									    }
									};
								else //corporate
									var currentRecipient = {
									  name : {
									      salutation : "",
									      givenName : "",
									      surName : "",
									    },
									  corporation : {
									      salutation : rec.company,
									      givenName : rec.forename,
									      surName : rec.surname,
									    },
									  address : {
									      residence : rec.street,
									      locality : rec.city,
									      postcode : rec.postal,
									      country : "",
									    }
									};

								recipients.push(currentRecipient);
							});
							
				

						var mailinfo = {
								'text': $('#message').val(),
								'receiver' : recipients				
							};
						self.ajax(targetURI, 'PUT', mailinfo, function(data){ 
							alert("mail sent");
							self.recipients(null);
							$('#message').val(null);
							self.current_order_price('EUR 00,00');
						});
					});
				});
			});

			
			//receivers
			//put: /mail/{mail-id}/receiver
			/*var targetURI = self.baseuri + "/mail/"+mailid+"/text";
			var text = $('#message').val();
			self.ajax(targetURI, 'PUT', items, function(data){ 
				console.log(data);
			});*/
		
		}
		
		self.showOrderDetails = function(order){
			var targetURI = self.baseuri + "/user/orders/"+order.id;
			self.ajax(targetURI, 'GET', null, function(data){ 

				var date = new Date(data.date);

				$('#orderdetails #val_orderid').html(self.parseOrderNumber(data.id));
				$('#orderdetails #val_orderdate').html(date);
				$('#orderdetails #val_orderstate').html(data.state);
				$('#orderdetails #val_orderprice').html(data.total);

				//destroy table
				$('#orderdetails #mails').html(null);

				$.each(data.items, function(index, value){
					var targetURI = self.baseuri + "/mail/"+value.id;
					self.ajax(targetURI, 'GET', null, function(data){ 
						$('#orderdetails #mails').append( '<tr><td>Status</td><td>' + data.status + '</td></tr>' );
						$('#orderdetails #mails').append( '<tr><td>Text</td><td>' + data.text + '</td></tr>' );

						$.each(data.receiver, function(index, receiver){

							var name = (receiver.name.surName)? 
								receiver.name.surName + ' ' + receiver.name.givenName :
								receiver.corporation.surName + ' ' + receiver.corporation.givenName +' (corp)' ;


							$('#orderdetails #mails').append( 
								'<tr><td>Receiver</td><td>' + name + '<br/>'+receiver.address.residence+'<br/>'+receiver.address.locality+' '+receiver.address.postcode+'</td></tr>' );
						});
					});
				});
			});
			$('#orderdetails').modal('show');

		}
		
		self.confirmOrder = function(order){
			var targetURI = self.baseuri + "/user/orders/"+order.id+"/confirm";
			self.ajax(targetURI, 'POST', null, function(data){ 
				console.log(data);
				self.initOrders();
			});
		}
		
		
	}
